package com.iwhalecloud.bss.kite.cucc.common.mq;

import com.alibaba.fastjson.JSON;
import com.iwhalecloud.bss.kite.client.dto.ExceptionLogDto;
import com.iwhalecloud.bss.kite.cucc.common.dto.RefreshCacheLogDTO;
import com.iwhalecloud.bss.kite.cucc.common.mq.producer.Producer;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;

/**
 * @author sunshaoqiang
 */
@Component
public class ExceptionLogProducer {

//    private static final ZLogger logger = ZLoggerFactory.getLogger(KiteLogProducer.class, "");

    @Value("${rocketmq.name-server}")
    private String addr;
    @Value("${rocketmq.exceptionLog.producer.topic}")
    private String topic;
    @Value("${rocketmq.access-key}")
    private String accessKey;
    @Value(("${rocketmq.exceptionLog.consumer.id}"))
    private String consumerId;
    @Value("${rocketmq.exceptionLog.producer.group}")
    private String groupId;
    @Value("${rocketmq.secret-key}")
    private String secretKey;
    @Value("${mq.env}")
    private String env;
    @Value("${rocketmq.exceptionLog.producer.id}")
    private String producerId;
    @Value("${rocketmq.sendMsgTimeoutMillis}")
    private String sendMsgTimeoutMillis;


    private IdWorker idWorker = new IdWorker(0L, 0L);

    public static final int MAX_LENGTH = 3 * 1000 * 1000;

    Producer producer;

    @PostConstruct
    public void initProducer() {
        producer = new Producer(producerId, accessKey, secretKey, sendMsgTimeoutMillis, addr, groupId, env);
        producer.start();
    }

    @PreDestroy
    public void closeProducer() {
        if (producer != null) {
            producer.shutdown();
        }
    }

    public void sendMessage(ExceptionLogDto exceptionLogDto, boolean isOneWay) {
        /**
         * MQ发送
         */
        producer.send(topic, "*", JSON.toJSONString(exceptionLogDto), String.valueOf(idWorker.nextId()), isOneWay);
    }

    public void sendMessageAsync(ExceptionLogDto exceptionLogDto) {
        /**
         * MQ发送
         */
        producer.sendAsync(topic, "*", JSON.toJSONString(exceptionLogDto), String.valueOf(idWorker.nextId()));
    }

}
